<?php

namespace Modules\Admin\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Admin\Entities\Admin;
use Modules\Admin\Http\Requests\AdminUserRequest;
use Spatie\Permission\Models\Role;

class AdminUserController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
    	$admins=Admin::where('name','<>','admin')->get();
        return view('admin::adminuser.index',compact('admins'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('admin::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(AdminUserRequest $request)
    {
    	$post=$request->all();
    	$post['password']=bcrypt($request->input('password'));
		Admin::create($post);
		//session()->flash('success','添加成功！');
		flash('添加成功！')->overlay ();
		return redirect ()->back();
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('admin::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit()
    {
        return view('admin::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(AdminUserRequest $request,$id)
    {
    	$admin=Admin::find($id);
    	$admin->name=$request->input('name');
    	$admin->nickname=$request->input('nickname');
    	if($request->input('password')){
    		$admin->password=bcrypt($request->input('password'));
		}
		$admin->save();
    	flash('修改成功！')->overlay ();
    	return redirect ()->back();
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {

    }
    public function del($id){
    	$admin=Admin::find($id);
    	$err=[];
    	if(Auth()->user ()->id==$id){
    		$err['error']=1;
    		$err['msg']='你想删除自己？是不是傻？';
		}else{
			if($admin->id!=1){
				Admin::destroy ($id);
				$err['error']=0;
				$err['msg']='删除成功！';
			}
		}
		echo json_encode($err);
	}
	public function showrole($id){
    	$roles=Role::get();
    	$admin=Admin::find($id);
    	return view('admin::adminuser.showrole',compact ('roles','admin'));
	}
	public function addrole(Request $request,$id){
    	if(!$request->input('name')){
    		flash('请至少选择一个角色！')->overlay ();
    		return redirect ()->back();
		}
		$admin=Admin::find($id);
		$admin->syncRoles($request->input('name'));
		flash('角色分配成功！')->overlay ();
		return redirect ('/admin/adminuser');
	}
}
